"use client";
/* eslint-disable react-hooks/rules-of-hooks */
import React, { useEffect, useState, useRef } from 'react';
import { useHotkeys } from 'react-hotkeys-hook';


const tileColors: { [key: number]: string; } = {
    0: "#CfC1B4",
    2: "#EEE4DA",
    4: "#EDE0C8",
    8: "#F2B179",
    16: "#F59563",
    32: "#F67C5F",
    64: "#F65E3B",
    128: "#EDCF72",
    256: "#EDCC61",
    512: "#EDC850",
    1024: "#EDC53F",
    2048: "#EDC22E"
};




// 定义页面组件
const page = () => {
    const [maps, setMaps] = useState<number[][]>([
        [0, 0, 0, 0],
        [0, 0, 0, 0],
        [0, 0, 0, 0],
        [0, 0, 0, 0]
    ]);
    const [isMove, setIsMove] = useState<boolean>(false);
    const [score, setScore] = useState(0);

    const [testPoint, setTestPoint] = useState();

    //随机生成2或4函数
    const getNumber = () => Math.random() > 0.1 ? 2 : 4;

    // 随机获取一个空白位置函数
    const getEmptySpacelist = () => {
        const emptySpace = [];
        for (let i = 0; i < 4; i++) {
            for (let j = 0; j < 4; j++) {
                if (maps[i][j] === 0) {
                    emptySpace.push([i, j]);
                }
            }
        }
        if (emptySpace.length === 0) {
            console.log('没有空余位置了');
        }
        return emptySpace[Math.floor(Math.random() * emptySpace.length)];
    };

    //空白位置添加元素
    const pushObject = () => {
        const position = getEmptySpacelist();
        if (!position) {
            console.error("没有空位置了！");
            return;
        }
        const [row, col] = position;
        const newmaps = structuredClone(maps);
        newmaps[row][col] = getNumber();
        setMaps(newmaps);
    };

    // 初始化页面
    useEffect(() => {
        pushObject();
    }, []);

    //帮助debug检测
    useEffect(() => {
        console.log(maps);
    }, [maps]);

    //监听是否发生移动，移动后单元格添加新元素
    useEffect(() => {
        if (isMove) {
            pushObject();
            setScore((prev) => prev + 1);
            setIsMove(false);
        }

    }, [isMove]);

    //处理单行元素移动、合并函数
    const handleNumCombine = (array: number[]): number[] => {
        const prevArray = structuredClone(array);
        const filterArray: number[] = array.filter((item) => item !== 0);
        const result: number[] = [];
        let i = 0;
        while (i <= filterArray.length - 1) {
            if (filterArray[i] === filterArray[i + 1]) {
                result.push(filterArray[i] * 2);
                i += 2;
            } else {
                result.push(filterArray[i]);
                i++;
            }
        }
        while (result.length < 4) {
            result.push(0);
        }
        return result;
    };


    //二维数组顺时针转90度
    const arrayTransposeAdd90 = (maps: number[][]) => {
        const newArray: number[][] = structuredClone(maps);
        for (let i = 0; i < maps.length; i++) {
            for (let j = 0; j < maps[i].length; j++) {
                newArray[j][i] = maps[i][j];
            }
        }
        const reverseNewArray = newArray.map((rows) => {
            return rows.reverse();
        });
        return reverseNewArray;
    };

    //二维数组逆时针转90度
    const arrayTransposeReduce90 = (maps: number[][]) => {
        const newArray: number[][] = structuredClone(maps);
        for (let i = 0; i < maps.length; i++) {
            for (let j = 0; j < maps[i].length; j++) {
                newArray[j][i] = maps[i][j];
            }
        }
        newArray.reverse();
        return newArray;
    };






    //方向左键事件
    useHotkeys('left', () => {
        const prevmaps = structuredClone(maps);
        //执行移动合并操作
        const newmaps: number[][] = [];
        //处理每行数据
        maps.map((rows) => {
            //处理单行元素数据
            const newrows: number[] = handleNumCombine(rows);
            newmaps.push(newrows);
            return newmaps;
        });
        setMaps(newmaps);
        //判断是否发生移动
        if (JSON.stringify(prevmaps) !== JSON.stringify(newmaps)) {
            setIsMove(true);
        } else {
            setIsMove(false);
        }
        console.log('按下了左键');
    });

    //方向右键事件
    useHotkeys('right', () => {
        const prevmaps = structuredClone(maps);
        //执行移动合并操作
        const newmaps: number[][] = [];
        //处理每行数据
        maps.map((rows) => {
            //处理单行元素数据
            rows.reverse();
            const newrows: number[] = handleNumCombine(rows);
            newrows.reverse();
            newmaps.push(newrows);
            return newmaps;
        });
        setMaps(newmaps);
        //判断是否发生移动
        if (JSON.stringify(prevmaps) !== JSON.stringify(newmaps)) {
            setIsMove(true);
        } else {
            setIsMove(false);
        }
        console.log('按下了右键');
    });

    useHotkeys("up", () => {
        const prevmaps = structuredClone(maps);
        console.log(prevmaps);
        //执行移动合并操作
        //二维数组顺时针旋转90度
        const transFormArray = arrayTransposeAdd90(maps);
        let newmaps: number[][] = [];
        //处理每行数据
        console.log(transFormArray);
        transFormArray.map((rows) => {
            //处理单行元素数据            
            rows.reverse();
            const newrows: number[] = handleNumCombine(rows);
            newrows.reverse();
            newmaps.push(newrows);
            return newmaps;
        });
        newmaps = arrayTransposeReduce90(newmaps);
        console.log(transFormArray);
        //二维数组逆时针旋转90度
        setMaps(newmaps);
        //判断是否发生移动
        if (JSON.stringify(prevmaps) !== JSON.stringify(newmaps)) {
            setIsMove(true);
        } else {
            setIsMove(false);
        }
        console.log('按下了上键');
    });

    useHotkeys("down", () => {
        const prevmaps = structuredClone(maps);
        console.log(prevmaps);
        //执行移动合并操作
        //二维数组顺时针旋转90度
        const transFormArray = arrayTransposeAdd90(maps);
        let newmaps: number[][] = [];
        //处理每行数据
        console.log(transFormArray);
        transFormArray.map((rows) => {
            //处理单行元素数据
            const newrows: number[] = handleNumCombine(rows);
            newmaps.push(newrows);
            console.log(newrows);
            return newmaps;
        });
        newmaps = arrayTransposeReduce90(newmaps);
        console.log(transFormArray);
        //二维数组逆时针旋转90度
        setMaps(newmaps);
        //判断是否发生移动
        if (JSON.stringify(prevmaps) !== JSON.stringify(newmaps)) {
            setIsMove(true);
        } else {
            setIsMove(false);
        }
        console.log('按下了下键');
    });

    //触摸操作事件

    const [swipeDirection, setSwipeDirection] = useState<string | null>(null);
    const startX = useRef<number>(0);
    const startY = useRef<number>(0);

    const handleTouchStart = (e: React.TouchEvent<HTMLDivElement>) => {
        const touch = e.touches[0];
        startX.current = touch.clientX;
        startY.current = touch.clientY;
    };

    const handleTouchMove = (e: React.TouchEvent<HTMLDivElement>) => {
        e.preventDefault();
        const touch = e.touches[0];
        const deltaX = touch.clientX - startX.current;
        const deltaY = touch.clientY - startY.current;

        // 判断滑动方向
        if (Math.abs(deltaX) > Math.abs(deltaY)) {
            // 水平滑动
            if (deltaX > 0) {
                setSwipeDirection("right");
            } else {
                setSwipeDirection("left");
            }
        } else {
            // 垂直滑动
            if (deltaY > 0) {
                setSwipeDirection("down");
            } else {
                setSwipeDirection("up");
            }
        }

        // 阻止默认行为（可选）

    };

    const handleTouchEnd = () => {
        setSwipeDirection(null); // 清空方向状态
    };



    return (

        <div onTouchStart={handleTouchStart} onTouchEnd={handleTouchEnd} onTouchMove={handleTouchMove} className='flex flex-col items-center min-w-screen'>
            <p>{swipeDirection}</p>
            <h1 className='m-3 font-douyin text-amber-900 text-2xl'>移动步数:{score}</h1>
            <p className='mb-3 font-douyin'>游戏规则：使用上下左右移动方块，相同数字碰撞数值会合并，目标合成出2048！</p>
            <div className='place-content-center place-items-center grid grid-cols-4 grid-rows-4 bg-base-200 shadow-2xl p-1 border rounded-2xl max-w-screen h- max-h-[400px] size-100'>
                {maps.map((rows, rowIndex) => {

                    return rows.map((cell, cellIndex) => {
                        const color: string = tileColors[cell];
                        return (
                            <div style={{ backgroundColor: color }} key={rowIndex + cellIndex + Math.random()} className='place-content-center place-items-center border-1 border-gray-600/50 rounded-2xl w-[90%] h-[90%]'>
                                <p className='font-douyin text-4xl'>{cell ? cell : null}</p>
                            </div>
                        );
                    });
                })}

            </div>

        </div>

    );
};

export default page;


